<template>
  <div class="return-order-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>进货退货管理</h2>
          <el-button type="primary" @click="addReturnOrder">新增退货单</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="退货单号">
          <el-input v-model="searchForm.returnOrderCode" placeholder="请输入退货单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="退货日期">
          <el-date-picker v-model="searchForm.returnDate" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column prop="returnOrderCode" label="退货单号" width="120"></el-table-column>
        <el-table-column prop="status" label="单据状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="outStatus" label="出库状态" width="100">
          <template #default="scope">
            <el-tag :type="getOutStatusType(scope.row.outStatus)">{{ getOutStatusText(scope.row.outStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="returnOrderDate" label="退货日期" width="150"></el-table-column>
        <el-table-column prop="purchaseOrderCode" label="进货单号" width="120"></el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="120"></el-table-column>
        <el-table-column prop="departmentName" label="部门" width="120"></el-table-column>
        <el-table-column prop="contact" label="联系人" width="100"></el-table-column>
        <el-table-column prop="contactPhone" label="联系方式" width="120"></el-table-column>
        <el-table-column prop="returnDesc" label="退货原因" min-width="150"></el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="150"></el-table-column>
        <el-table-column prop="creator" label="创建人" width="100"></el-table-column>
        <el-table-column prop="createDate" label="创建日期" width="150"></el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange"></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';

// 路由
const router = useRouter();

// 搜索表单
const searchForm = reactive({
  returnOrderCode: '',
  returnDate: []
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 初始化
onMounted(() => {
  loadData();
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  // 如果日期已经是格式化的，直接返回
  if (dateString.includes('-') && dateString.length >= 10) {
    return dateString.substring(0, 10);
  }

  try {
    const date = new Date(dateString);
    return date.toISOString().split('T')[0];
  } catch (e) {
    return dateString;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1: return '草稿';
    case 2: return '待审批';
    case 3: return '已审批';
    case 4: return '已拒绝';
    default: return '未知状态';
  }
};

// 获取状态对应的类型
const getStatusType = (status) => {
  switch (status) {
    case 1: return ''; // 草稿
    case 2: return 'warning'; // 待审批
    case 3: return 'success'; // 已审批
    case 4: return 'danger'; // 已拒绝
    default: return '';
  }
};

// 获取出库状态文本
const getOutStatusText = (outStatus) => {
  switch (outStatus) {
    case 1: return '待出库';
    case 2: return '已出库';
    default: return '未知状态';
  }
};

// 获取出库状态对应的类型
const getOutStatusType = (outStatus) => {
  switch (outStatus) {
    case 1: return 'warning'; // 待出库
    case 2: return 'success'; // 已出库
    default: return '';
  }
};

// 加载表格数据
const loadData = () => {
  loading.value = true;

  // 构建查询参数
  const params = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value
  };

  if (searchForm.returnOrderCode) {
    params.returnOrderCode = searchForm.returnOrderCode;
  }

  if (searchForm.returnDate && searchForm.returnDate.length === 2) {
    params.startDate = searchForm.returnDate[0];
    params.endDate = searchForm.returnDate[1];
  }
  
  // 调用后端API - 使用与curl命令一致的路径
  axios.get(`/api/ReturnOrder/page`, { 
    params: {
      pageIndex: params.pageIndex,
      pageSize: params.pageSize
    }
  })
    .then(response => {
      console.log('API返回数据:', response.data);
      if (response.data && response.data.code === 200) {
        // 将后端返回的数据转换为前端表格需要的格式
        const data = response.data.data || [];

        // 处理数据，确保日期格式正确
        tableData.value = data.map(item => {
          // 确保日期格式正确
          if (item.returnOrderDate) {
            item.returnOrderDate = formatDate(item.returnOrderDate);
          }
          if (item.createDate) {
            item.createDate = formatDate(item.createDate);
          }
          if (item.modifyDate) {
            item.modifyDate = formatDate(item.modifyDate);
          }

          return item;
        });

        total.value = response.data.totalCount || data.length || 0;
      } else {
        ElMessage.error(response.data?.message || '获取数据失败');
        tableData.value = [];
        total.value = 0;
      }
    })
    .catch(error => {
      console.error('获取数据失败:', error);
      ElMessage.error('获取数据失败，请检查网络连接');
      tableData.value = [];
      total.value = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = [];
    } else {
      searchForm[key] = '';
    }
  });
  handleSearch();
};

// 分页相关
const handleSizeChange = (size) => {
  pageSize.value = size;
  console.log('改变每页显示数量:', size);
  loadData();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  console.log('改变当前页:', page);
  loadData();
};

// 新增退货单
const addReturnOrder = () => {
  router.push('/ReturnOrderEdit');
};
</script>

<style scoped>
.return-order-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>